package com.buka.listener;


import com.buka.config.RabbitMqConfig;
import com.buka.entity.Result;
import com.buka.feign.OrderFeign;
import com.buka.pay.AliPay;
import com.buka.pojo.Order;
import com.buka.service.AliPayService;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;

import java.util.Map;
import java.util.concurrent.TimeUnit;

@Component
public class PayListener {
    @Autowired
    private AliPayService aliPayService;
    @Autowired
    private RedisTemplate redisTemplate;
    @Autowired
    private RabbitTemplate rabbitTemplate;
    @Autowired
    private OrderFeign orderFeign;
    //GoodsListener传的Order
    @RabbitListener(queues = RabbitMqConfig.ALIPAY_QUEUE)
    public void Pay(Order order){
        AliPay aliPay=new AliPay();
        aliPay.setOutTradeNo(order.getId().toString());
        aliPay.setTotalAmount(order.getMoney());
        aliPay.setSubject("商品购买");
        String form = aliPayService.H5Pay(aliPay);
        System.out.println(form);
        redisTemplate.opsForValue().set("Pay_"+order.getId(),form,30, TimeUnit.MINUTES);
        rabbitTemplate.convertAndSend("",RabbitMqConfig.PAY_QUEUE,order);
    }

    @RabbitListener(queues = RabbitMqConfig.TIME_OUT_QUEUE)
    public void Out_Time_Pay(Order order){
        //检测订单是否支付
       order=  orderFeign.findById(order.getId()).getData();
       if(order.getStatus()==0&&order!=null){
           //没支付
           AliPay aliPay=new AliPay();
           aliPay.setOutTradeNo(order.getId().toString());
           Map<String, String> query = aliPayService.query(aliPay);
           if(query.get("msg").equals("success")){
                //成功支付就补偿
               order.setTradeNo(query.get("trade_no"));
               order.setStatus(2);
                rabbitTemplate.convertAndSend("",RabbitMqConfig.NOTIFY_QUEUE,order);
           }else {
                //超时订单就关闭
               aliPayService.close(aliPay);

               //回滚库存
               rabbitTemplate.convertAndSend("",RabbitMqConfig.ADD_INVENTORY_QUEUE,order);

               //订单状态改为已关闭
               order.setStatus(7);
               rabbitTemplate.convertAndSend("",RabbitMqConfig.NOTIFY_QUEUE,order);
           }
       }
    }

}
